<?php

namespace app\common\upload;

use app\common\service\WeginService;
use EasyAdmin\upload\FileBase;
use EasyAdmin\upload\trigger\SaveDb;
use think\facade\Filesystem;

/**
 * 通过weiq配置公众号的云存储来保存附件
 */
class We7Driver extends FileBase
{
    public function save()
    {
        //把文件上传到we7 的attachment目录下
        $this->completeFilePath = Filesystem::disk('public')->putFile('upload', $this->file);
        //得到上传后的url
        $relative_dir = str_replace('attachment','',config('filesystem.disks.public.url'));
        $relative_dir = ltrim($relative_dir,'/');
        //去除attachment部分，file_remote_upload函数不需要这部分
        $this->completeFileUrl = $relative_dir   . str_replace(DIRECTORY_SEPARATOR, '/', $this->completeFilePath);

        @require_once (IA_ROOT . '/framework/function/file.func.php');

        @file_remote_upload($this->completeFileUrl);
        //如果we7存储在本地就采用本地路径
        $uni_remote_setting = uni_setting_load('remote');
        if (!empty($uni_remote_setting['remote']['type'])){
            $back_url = tomedia($this->completeFileUrl);
        }else{
            $back_url = "/attachment/". $this->completeFileUrl;
        }

        SaveDb::trigger($this->tableName, [
            'uniacid'=> WeginService::getUniacid(),
            'upload_type'   => 'local',
            'original_name' => $this->file->getOriginalName(),
            'mime_type'     => $this->file->getOriginalMime(),
            'file_ext'      => strtolower($this->file->getOriginalExtension()),
            'url'           => $back_url,
            'create_time'   => time(),
        ]);
        return [
            'save' => true,
            'msg'  => '上传成功',
            'url'  => $back_url,
        ];
    }
}